/******************************************************************************************************
Copyright (C) 2008 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals
        nmr, mainWindow, print, DBPlugin, MessageBox, NMRSpectrum, dbGetNMRPoints */
/*jslint plusplus: true, indent: 4*/

// Retrieve records for all given hits and paste them into Mnova, return list of retrieved molecules
function retrieveHits(aDB, aHits) {
    "use strict";
    var h, aux, items, i,
        //page = main.newPage(),
        docs = [],
        molecules = [];
    for (h = 0; h < aHits.length; h++) {
        aux = mainWindow.newWindow();
        docs.push(aux);
        DBPlugin.getRecord(aDB, aHits.at(h).recordId());
        items = aux.itemCount();
        for (i = 0; i < items; i++) {
            if (aux.item(i).name === "Molecule") {
                //page.addItem(aux.item(i));
                molecules.push(aux.item(i));
            }
        }
    }
    return molecules;
}

// Builds a spectrum similarity query from the given NMR spectrum.
function dbGetSpectrumQuery(aNMRSpectrum) {
    "use strict";
    var pointsJSON, points, query;
    // dbGetNMRPoints(aNMRSpectrum, aDim, aNumBins) from DBPLugin.qs returns JSON string with the fields points, numPoints, numPointsOrig
    pointsJSON = dbGetNMRPoints(aNMRSpectrum, 1, 10);
    points = JSON.parse(pointsJSON);
    //print("Points: " + points);
    query = points;
    query.method = "COSINE";      // Needed: COSINE, TREESIM, STANSIM
    query.itemType = "1D";        // Needed: 1D, 2D, ElViS
    return query;
}

// ======================================================================================================

function dbSpectrumSearchExample() {
    "use strict";
    var query, queryJSON, hits, h,
        db = DBPlugin.client,
        spec = nmr.activeSpectrum();

    if (!db.connected()) {
        MessageBox.critical("Not connected to database.");
        return;
    }

    if (!spec) {
        MessageBox.critical("Need an NMR spectrum for this example..");
        return;
    }

    query = dbGetSpectrumQuery(spec);
    queryJSON = JSON.stringify(query);
    print("Query JSON: " + queryJSON);

    hits = DBPlugin.search(db, queryJSON, "SPECTRUM", "", "", 10, 10, 600);
    print("Hits: " + hits.length);
    for (h = 0; h < hits.length; h++) {
        print("    Hit: " + hits.at(h).toString());
    }

    //retrieveHits(db, hits);     // Uncomment this line to retrieve records from db to Mnova
    // db.disconnect();
}




